package com.lunhui.user.business.impl;

import com.lunhui.user.business.UserService;
import com.lunhui.user.business.utlis.Utils;
import com.lunhui.user.dal.dao.UserDao;
import com.lunhui.user.dal.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author renminghe-kg
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    @Qualifier("userDao")
    private UserDao userDao;

    @Override
    public Integer saveToDB(String account, String password) {
        try {

            String nowDateStr = Utils.nowDate();

            User user = new User();
            user.setUserId(0);
            user.setAccount(account);
            user.setPassword(Utils.MD5(password));
            user.setCreateTime(nowDateStr);
            user.setLastLoginTime(nowDateStr);

            return userDao.save(user);

        } catch (Exception e) {
            logger.error("保存账户信息失败: " + e.getMessage());
            throw new RuntimeException("保存账户信息失败: " + e.getMessage());
        }
    }

    @Override
    public User getByAccount(String account) {
        try {

            User user = new User();
            user.setAccount(account);

            return userDao.getByAccount(user);

        } catch (Exception e) {
            logger.error("获取账户信息失败: " + e.getMessage());
            throw new RuntimeException("获取账户信息失败: " + e.getMessage());
        }
    }

    @Override
    public User getByAccountAndPassword(String account, String password) throws Exception {
        try {

            User user = new User();
            user.setAccount(account);
            user.setPassword(Utils.MD5(password));

            return userDao.getByAccountAndPassword(user);

        } catch (Exception e) {
            logger.error("获取账户信息失败: " + e.getMessage());
            throw new RuntimeException("获取账户信息失败: " + e.getMessage());
        }
    }

    @Override
    public Integer updateUserInfo(User user) throws Exception {
        return userDao.update(user);
    }
}